<?php
declare(strict_types=1);

namespace app\api\logic;

use app\admin\model\order\Order;
use app\admin\model\order\OrderGoods;
use app\admin\model\user\UserMember;
use app\basic\BaseLogic;
use app\basic\model\UserThird;
use app\api\service\payment\{BalancePayment, WechatPayment, AlipayPayment};
use app\admin\model\User;
use think\facade\Db;

class PayLogic extends BaseLogic
{
    protected $orderModel;
    protected $userModel;

    protected $error;


    public function __construct()
    {
        $this->model = new Order();
        $this->orderModel = $this->model;
        $this->userModel = new UserMember();
    }

    /**
     * 支付
     */
    public function pay($userId, $params)
    {
        // 参数验证
        if (empty($params['order_id']) || empty($params['pay_type'])) {
             $this->setError('参数错误');
            return false;
        }
        // 获取订单信息
        $order = $this->orderModel->where([
            'order_id' => $params['order_id'],
            'user_id' => $userId,
            'pay_status' => 10,
            'order_status' => 10
        ])->find();

        if (empty($order)) {
             $this->setError('订单不存在或已支付');
             return false;
        }

        // 创建支付实例
        $payment = $this->createPayment($params['pay_type']);
        if (!$payment) {
             $this->setError('不支持的支付方式');
             return false;
        }
        $openid = '';
        // 根据支付方式查询 openid
        if($params['pay_type'] == 2){
            $openid = (new UserThird())->where(['user_id'=>$userId,'type' => $params['client']])->value("openid");
        }
        $goods_name = OrderGoods::where('order_id', $order['order_id'])->value("goods_name");
        // 调用支付
        $result = $payment->pay([
            'order_id' => $order['order_id'],
            'order_no' => $order['order_no'],
            'body' => $goods_name,
            'total_amount' => $order['pay_price'],
            'openid' => $openid,
            'pay_scene' => $params['client'],
            'user_id' =>$userId
        ]);
        if (!$result) {
             $this->setError($payment->getError());
             return false;
        }
        return $result;
    }

    /**
     * 创建支付实例
     */
    protected function createPayment($payType)
    {
        switch ($payType) {
            case 1:
                return new BalancePayment($this->orderModel, $this->userModel);
            case 2:
                return new WechatPayment($this->orderModel);
            case 3:
                return new AlipayPayment($this->orderModel);
            default:
                return null;
        }
    }

    /**
     * 微信回调
     */
    public function payNotify($params,$payType)
    {
        // 创建支付实例
        $payment = $this->createPayment($payType);
        if (!$payment) {
             $this->setError('不支持的支付方式');
             return false;
        }
        $result = $payment->handleNotify($params);
        write_log($result, runtime_path().'/wechat_notify');
        // 根据支付失败还是成功 处理订单回调后的问题
        if ($result['code'] == 'SUCCESS') {
            // 处理支付成功 重新组装数组
            $result = [
                'order_no' => $result['data']['resource']['ciphertext']['out_trade_no'],
                'transaction_id' => $result['data']['resource']['ciphertext']['transaction_id']
            ];
            $this->handlePaySuccess($result);
        }
        return $payment->confirmNotify();
    }

     /**
     * 处理支付成功
     * @param array $order
     * @return bool
     */
    public function handlePaySuccess($arr)
    {
        $order = $this->orderModel->where('order_no', $arr['order_no'])->find();
        Db::startTrans();
        try {
            // 更新订单状态
            $this->orderModel->where('order_id', $order['order_id'])->update([
                'pay_status' => 20,
                'pay_time' => time(),
                'update_time' => time()
            ]);
            // 根据订单类型处理不同的业务逻辑
            if ($order['order_type'] == 1) {
                // 添加用户文档记录
                (new UserDocLogic())->handleOrderPaid($order['order_id'],$order['user_id']);
            } else if ($order['order_type'] == 2) {
               (new UserVipCardLogic())->handleOrderPaid($order['order_id'], $order['user_id']);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }

      public function setError($error)
    {
        $this->error = $error;
    }

    public function getError()
    {
        return $this->error;
    }

}